<?php

if (!defined('LACONICA')) {
    exit(1);
}

require_once INSTALLDIR.'/classes/User.php';

class Imbot_Handle
{
    /** Current group, group query. */
    var $url = 'https://www.imified.com/api/bot/';
    var $bot_key = '';
    var $user_pass = '';
    
    function excute($data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERPWD, $this->user_pass);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 100);
        $xml = curl_exec($ch);
        curl_close($ch);
        
        if(!is_null($xml) && !empty($xml))
            return $xml;  
        return false;
    }
    
    function sendMessage($userkey,$message)
    {
        $datasend=array(
        'botkey' => $this->bot_key,
        'apimethod' => 'send',
        'userkey' => $userkey,
        'msg'=> $message,
        );     
        return $this->excute($datasend);
    }
    
    function sendMessageStatic($userkey,$message)
    {
        $datasend=array(
        'botkey' => $this->bot_key,
        'apimethod' => 'send',
        'userkey' => $userkey,
        'msg'=> $message,
        );     
        return $this->excute($datasend);
    }
    
    function getUser($userkey)
    {
        $dataget=array(
        'botkey' => $this->bot_key,
        'apimethod' => 'getuser',
        'userkey' => $userkey,
        );
        return $this->excute($dataget);
    }
    
    static function checkFail($xml)
    {
         $doc  = simplexml_load_string($xml); 
         $stat = $doc->attributes();
         if(strtolower($stat['stat']=='fail'))
         {
            return true;
         } 
         return false;
    
    }
    static function getError($xml)
    {
         $doc  = simplexml_load_string($xml); 
         $stat = $doc->err[0]->attributes();
         if(!$stat || $doc)
         {
            return false;
         } 
         return $stat['msg'];
    
    }
    function get_user($fromuser_key)
    {
        $user = User::staticGet('im_userkey', $fromuser_key);
        return $user;
    }
    
    function handle_message($userkey,$network,$msg,$valuex,$step)
    {
        if (mb_strlen($msg) == 0) {
            return;
        }
        
        if (strtolower($msg)=='userkey') {
            echo 'User key cua ban la : '.$userkey;
            return ;
        }
        
        
        $user = $this->get_user($userkey);
        
        if (!$user) {
            $this->from_site($userkey, 'Thanh vien chua xac dinh; ban hay vao ' .
                             common_local_url('imsettings') .
                             ' de nhap dia chi IM vao tai khoan cua ban.');
            $this->log(LOG_WARNING, 'Message from unknown user ' . $userkey);
            return;
        }
        if ($this->handle_command($user, $msg)) {
            return;
        }else if ($this->is_autoreply($msg)) {
            $this->log(LOG_INFO, 'Ignoring auto reply from ' . $userkey);
            return;
        } else if ($this->is_otr($msg)) {
            $this->log(LOG_INFO, 'Ignoring OTR from ' . $userkey);
            return;
        } else if ($this->is_direct($msg)) {
            preg_match_all('/d[\ ]*([a-z0-9]{1,64})/', $msg, $to);
            $to = preg_replace('/^d([\ ])*/', '', $to[0][0]);
            $body = preg_replace('/d[\ ]*('. $to .')[\ ]*/', '', $msg);
         
         // Need to see here add_direct Function, and the $form value
            $this->add_direct($user, $body, $to, $userkey);
            
         //---------------------------------------------------------//
        } else {
            $len = mb_strlen($msg);
            if($len > 140) {
                echo 'Tin nhan cua ban qua dai, nhieu hon 140 ky tu. Ban da danh:  '.$len. ' ký tự';
             //   $this->from_site($from, 'Message too long - maximum is 140 characters, you sent ' . $len);
                return;
            }
            
            // Need to see here add_notice Function, and the $pl value
            
            $this->add_notice($user, $msg,$this->whereyoufrom($network));
            //---------------------------------------------------------//
        }

        $user->free();
        unset($user);
    }
    
    function from_site($address, $msg)
    {
        $text = '[Toi24h.com] ' . $msg;
        echo $text;
    }
    
    function log($level, $msg)
    {
        common_log($level, 'XMPPDaemon('.$this->resource.'): '.$msg);
    }

    function is_direct($txt)
    {
        if (strtolower(substr($txt, 0, 2))=='d ') {
            return true;
        } else {
            return false;
        }
    }
    function is_autoreply($txt)
    {
        if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
            return true;
        } else {
            return false;
        }
    }
    
    function is_otr($txt)
    {
        if (preg_match('/^\?OTR/', $txt)) {
            return true;
        } else {
            return false;
        }
    }
    
    function handle_command($user, $body)
    {
        $inter = new CommandInterpreter();
        $cmd = $inter->handle_command($user, $body);
        if ($cmd) {
            
            //Need to have a new channel here ???
            $chan = new XMPPChannel($this->conn);
         
            //--------------------------------------------//
            //Need to have a new channel here ???   
            $cmd->execute($chan);
            return true;
        } else {
            return false;
        }
    }
    
     function add_notice(&$user, &$msg,$where)
    {
        $body = trim($msg);
        $content_shortened = common_shorten_link($body);
        if (mb_strlen($content_shortened) > 140) {
            $content = trim(mb_substr($body, 0, 140));
            $content_shortened = common_shorten_link($content);
        }
        else {
            $content = $body;
        }
        
        $content=stripslashes($content);
        
        //Should i need to change xmpp here to IM?
        $notice = Notice::saveNew($user->id, $content, $where);
        if (is_string($notice)) {
            $this->log(LOG_ERR, $notice);
            return;
        }
        echo "[Toi24h.com] Tin nhan cua ban da duoc dang len Toi24h";
        common_broadcast_notice($notice);
        $this->log(LOG_INFO,
                   'Added notice ' . $notice->id . ' from user ' . $user->nickname);
        $notice->free();
        unset($notice);
    }
    
    function whereyoufrom($network)
    {
        switch(strtolower($network))
        {
            case 'yahoo':
                return "Y!M";
                break;
            case 'jabber':
                return "Gtalk/Jabber";
                break;
            case 'msn':
                return "msn";
                break;
            case 'aim':
                return "aim";
                break;
        }
    }



    
}

